package cn.sinata.wanglin.property.fragment;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.xilada.xldutils.activitys.WebViewActivity;
import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.adapter.LoopVPAdapter;
import com.xilada.xldutils.fragment.BaseLazyFragment;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.DialogUtils;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;
import com.xilada.xldutils.view.BannerLayout;
import com.xilada.xldutils.view.SwipeRefreshRecyclerLayout;
import com.xilada.xldutils.view.utils.ViewHolder;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.sinata.wanglin.MainActivity;
import cn.sinata.wanglin.MyApplication;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.adapter.ProperNoticeAdapter;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.model.Banner;
import cn.sinata.wanglin.model.ProperNotice;
import cn.sinata.wanglin.model.PropertyHome;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import cn.sinata.wanglin.property.activity.BossMailboxActivity;
import cn.sinata.wanglin.property.activity.ExpressDeliveryActivity;
import cn.sinata.wanglin.property.activity.OwnerCertificationActivity;
import cn.sinata.wanglin.property.activity.PraiseAndCriticizeActivity;
import cn.sinata.wanglin.property.activity.ProperNoticeDetailActivity;
import cn.sinata.wanglin.property.activity.PropertyCompanyActivity;
import cn.sinata.wanglin.property.activity.PropertyRepairActivity;
import cn.sinata.wanglin.property.activity.SuggestionsActivity;
import cn.sinata.wanglin.utils.ImageUtil;
import cn.sinata.wanglin.utils.RxBus;
import cn.sinata.wanglin.village.activity.ChoiceVillageActivity;
import rx.Observable;
import rx.functions.Action1;

/**
 * description：
 * Created by kaihongwu on 2016/12/05 下午 12:00
 */
public class PropertyFragment extends BaseLazyFragment implements View.OnClickListener ,SwipeRefreshRecyclerLayout.OnRefreshListener{
    private ProperNoticeAdapter mProperNoticeAdapter;
    private List<ProperNotice> mProperNotice=new ArrayList<ProperNotice>();
    @BindView(R.id.mSwipeRefreshLayout)
    SwipeRefreshRecyclerLayout mSwipeRefreshLayout;//
    @BindView(R.id.title)
    TextView titleView;
    @BindView(R.id.image)
    SimpleDraweeView companyImageView;
    private View tv_no_company;
    private BannerLayout bannerLayout;
    private View ll_not_auth;
    private String housingId;
    private String userId;
    private int pageNo = 0;
    private String companyId;
    private BannerAdapter bannerAdapter;
    private ArrayList<Banner> mBanners = new ArrayList<>();
    private PropertyHome mPropertyHome;
    private Observable<String> deleteVillageOb ;

    protected RecyclerView.Adapter setAdapter() {
        mProperNoticeAdapter = new ProperNoticeAdapter(mProperNotice);
        View headerView = LayoutInflater.from(context).inflate(R.layout.header_fragment_property,null);
        ll_not_auth = headerView.findViewById(R.id.ll_not_auth);
        bannerLayout = (BannerLayout) headerView.findViewById(R.id.banner);
        View tv_praiseandcriticize = headerView.findViewById(R.id.tv_praiseandcriticize);
        View tv_expressdelivery = headerView.findViewById(R.id.tv_expressdelivery);
        View tv_propertypayment = headerView.findViewById(R.id.tv_propertypayment);
        View tv_communitytoraisepublic = headerView.findViewById(R.id.tv_communitytoraisepublic);
        View tv_bossmailbox = headerView.findViewById(R.id.tv_bossmailbox);
        View tv_suggestions = headerView.findViewById(R.id.tv_suggestions);
        View tv_propertyrepair = headerView.findViewById(R.id.tv_propertyrepair);
        View tv_go_auth = headerView.findViewById(R.id.tv_go_auth);
        View tv_morefunction = headerView.findViewById(R.id.tv_morefunction);
        tv_no_company = headerView.findViewById(R.id.tv_no_company);
        tv_praiseandcriticize.setOnClickListener(this);
        tv_expressdelivery.setOnClickListener(this);
        tv_propertypayment.setOnClickListener(this);
        tv_communitytoraisepublic.setOnClickListener(this);
        tv_bossmailbox.setOnClickListener(this);
        tv_suggestions.setOnClickListener(this);
        tv_propertyrepair.setOnClickListener(this);
        tv_go_auth.setOnClickListener(this);
        tv_morefunction.setOnClickListener(this);

        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        headerView.setLayoutParams(params);
        mProperNoticeAdapter.setHeaderView(headerView);
        bannerLayout.setInterval(2*1000);
        bannerAdapter = new BannerAdapter(context,mBanners,bannerLayout.getAutoScrollViewPager());
        bannerLayout.setAdapter(bannerAdapter);

        mProperNoticeAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ActivityUtil.create(PropertyFragment.this)
                        .go(ProperNoticeDetailActivity.class)
                        .put("data",mProperNotice.get(position))
                        .startForResult(16);
            }
        });
        return mProperNoticeAdapter;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_property;
    }

    @Override
    protected void onFirstVisibleToUser() {

        mSwipeRefreshLayout.addItemDecoration(new HorizontalDividerItemDecoration.Builder(context)
                .colorResId(R.color.dividing_line_color)
                .size(1)
                .build());
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setLayoutManager(new LinearLayoutManager(context));
        mSwipeRefreshLayout.setMode(SwipeRefreshRecyclerLayout.Mode.Both);
        mSwipeRefreshLayout.setAdapter(setAdapter());

        userId = SharedPreferencesUtils.getString(Constant.SP_USERID);
        housingId = MyApplication.houseid;

        companyImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPropertyHome.getCompanyId().equals("0")) {
                    showToast("该小区暂无物业信息！");
                    return;
                }
                if (mPropertyHome.getApprove() != 1) {
                    showNoAuthDialog();
                } else {
                    ActivityUtil.create(context)
                            .go(PropertyCompanyActivity.class)
                            .put("id",mPropertyHome.getCompanyId())
                            .start();
                }
            }
        });

        titleView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtil.create(PropertyFragment.this)
                        .go(ChoiceVillageActivity.class)
                        .startForResult(0);
            }
        });

        deleteVillageOb = RxBus.get().register(Constant.DELETE_VILLAGE_ACTION,String.class);

        deleteVillageOb.subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                Utils.systemErr("--deleteVillageOb-->"+s);
                housingId = MyApplication.houseid;
                //如果删除的小区是当前选择的小区。刷新页面数据
                if (TextUtils.equals(housingId, s)) {
                    getData();
                }
            }
        });

        //如果选择小区为空或没选择小区。
        if (TextUtils.equals("-1", housingId) || TextUtils.isEmpty(housingId)) {
            ActivityUtil.create(this)
                    .go(ChoiceVillageActivity.class)
                    .startForResult(0);
        } else {
            titleView.setText(MyApplication.houseName);
            showDialog();
            getData();
        }
    }

    @Override
    protected void onVisibleToUser() {
        if (context instanceof MainActivity) {
            int index = ((MainActivity) context).getCurrentTab();
            if (index == 3) {
                housingId = MyApplication.houseid;
                String oldTitle = titleView.getText().toString();
                if (!TextUtils.equals(oldTitle, MyApplication.houseName) && !TextUtils.isEmpty(housingId)
                        && !TextUtils.equals("-1",housingId)) {
                    showDialog();
                    getData();
                } else {
                    if (mPropertyHome == null) {
                        showDialog();
                        getData();
                    }
                }
                titleView.setText(MyApplication.houseName);
                if (mBanners.size() > 0) {
                    bannerLayout.startAutoScroll();
                } else {
                    bannerLayout.stopAutoScroll();
                }
            }
        }
    }

    @Override
    protected void onInvisibleToUser() {
        if (mBanners.size() > 0) {
            bannerLayout.stopAutoScroll();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 0 ) {
                if (data!=null) {
                    housingId = MyApplication.houseid;
                    titleView.setText(MyApplication.houseName);
                    showDialog();
                    getData();
                }
            } else if (requestCode == 16) {
                showDialog();
                getData();
            } else if (requestCode == 22) {
                showDialog();
                getData();
            }
        }
    }

    void getData(){
        if (housingId == null) {
            housingId = "";
        }
        HttpManager.getTenement(housingId,userId,pageNo)
                .subscribe(new ResultDataSubscriber<PropertyHome>(this) {
                    @Override
                    public void onSuccess(String msg, PropertyHome propertyHome) {
                        mPropertyHome=propertyHome;
                        mSwipeRefreshLayout.setRefreshing(false);
                        companyImageView.setImageURI(ImageUtil.parseImageUri(propertyHome.getCompanyImg()));

                        companyId = propertyHome.getCompanyId();

                        if (pageNo == 0) {
                            mProperNotice.clear();
                            if (companyId.equals("0")) {
                                tv_no_company.setVisibility(View.VISIBLE);
                            } else {
                                tv_no_company.setVisibility(View.GONE);
                                //小区认证状态（0：待审核，1：审核通过，2：审核不通过，3未提交认证）
                                if (propertyHome.getApprove() == 3) {
                                    ll_not_auth.setVisibility(View.VISIBLE);
                                } else {
                                    ll_not_auth.setVisibility(View.GONE);
                                }
                            }
                        }

                        mBanners.clear();
                        if (propertyHome.getBanner() != null) {
                            mBanners.addAll(propertyHome.getBanner());
                        }
                        bannerAdapter = new BannerAdapter(context,mBanners,bannerLayout.getAutoScrollViewPager());
                        bannerLayout.setAdapter(bannerAdapter);
                        if (mBanners.size() > 0) {
                            bannerLayout.startAutoScroll();
                        }
                        if (propertyHome.getHousingNotice() != null) {
                            mProperNotice.addAll(propertyHome.getHousingNotice());
                        }
                        mProperNoticeAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                });
    }

    void showNoAuthDialog(){
        if (mPropertyHome.getApprove() == 0) {
            showToast("您的资料还在审核中,请耐心等候...");
            return;
        }
        String s =  "您还未完成该小区认证，无法进行此操作。";
        if (mPropertyHome.getApprove() == 2) {
            s = "您的资料未能通过审核,请重新提交认证";
        }
        DialogUtils.createNoticeDialog(context, "请注意",s, "前往认证", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ActivityUtil.create(getActivity()).go(OwnerCertificationActivity.class)
                        .startForResult(22);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_praiseandcriticize:
                if (mPropertyHome.getCompanyId().equals("0")) {
//                    showToast("该小区暂无物业信息！");
                    showNoCompany();
                    return;
                }
                if (mPropertyHome.getApprove() != 1) {
                    showNoAuthDialog();
                } else {
                    //描述:批评表扬
                    ActivityUtil.create(getActivity()).go(PraiseAndCriticizeActivity.class)
                            .put("id",companyId)
                            .start();
                }

                break;
            case R.id.tv_expressdelivery:
                if (mPropertyHome.getCompanyId().equals("0")) {
//                    showToast("该小区暂无物业信息！");
                    showNoCompany();
                    return;
                }
                if (mPropertyHome.getApprove() != 1) {
                    showNoAuthDialog();
                } else {
                    //描述:快递领物
                    ActivityUtil.create(getActivity()).go(ExpressDeliveryActivity.class)
                            .start();
                }
                break;
            case R.id.tv_propertypayment:
                //描述:物业缴费
                showToast("即将上线，敬请期待...");
                break;
            case R.id.tv_communitytoraisepublic:
                //描述:小区众筹
                showToast("即将上线，敬请期待...");
                break;
            case R.id.tv_bossmailbox:
                if (mPropertyHome.getCompanyId().equals("0")) {
//                    showToast("该小区暂无物业信息！");
                    showNoCompany();
                    return;
                }
                if (mPropertyHome.getApprove() != 1) {
                    showNoAuthDialog();
                } else {
                    //描述:BOSS信箱
                    ActivityUtil.create(getActivity()).go(BossMailboxActivity.class)
                            .put("id", companyId)
                            .start();
                }
                break;
            case R.id.tv_suggestions:
                if (mPropertyHome.getCompanyId().equals("0")) {
//                    showToast("该小区暂无物业信息！");
                    showNoCompany();
                    return;
                }
                if (mPropertyHome.getApprove() != 1) {
                    showNoAuthDialog();
                } else {
                    //描述:建议献策
                    ActivityUtil.create(getActivity()).go(SuggestionsActivity.class)
                            .put("id", companyId)
                            .start();
                }
                break;
            case R.id.tv_propertyrepair:
                if (mPropertyHome.getCompanyId().equals("0")) {
//                    showToast("该小区暂无物业信息！");
                    showNoCompany();
                    return;
                }
                if (mPropertyHome.getApprove() != 1) {
                    showNoAuthDialog();
                } else {
                    //描述:物业保修
                    ActivityUtil.create(getActivity()).go(PropertyRepairActivity.class)
                            .start();
                }
                break;
            case R.id.tv_go_auth:
                ActivityUtil.create(getActivity()).go(OwnerCertificationActivity.class)
                        .startForResult(22);
                break;
            case R.id.tv_morefunction:
                showToast("即将上线，敬请期待...");
                break;
        }
    }

    void showNoCompany(){
        DialogUtils.createNoticeDialog(context,"请注意","该小区即将入驻物业");
    }

    @Override
    public void onRefresh() {
        housingId = MyApplication.houseid;
        if (TextUtils.equals("-1", housingId) || TextUtils.isEmpty(housingId)) {
            mSwipeRefreshLayout.setRefreshing(false);
            ActivityUtil.create(this)
                    .go(ChoiceVillageActivity.class)
                    .startForResult(0);
        } else {
            pageNo = 0;
            getData();
        }
    }

    @Override
    public void onLoadMore() {
        housingId = MyApplication.houseid;
        if (TextUtils.equals("-1", housingId) || TextUtils.isEmpty(housingId)) {
            mSwipeRefreshLayout.setRefreshing(false);
            ActivityUtil.create(this)
                    .go(ChoiceVillageActivity.class)
                    .startForResult(0);
        } else {
            pageNo++;
            getData();
        }
    }

    private class BannerAdapter extends LoopVPAdapter<Banner> {


        public BannerAdapter(Context context, ArrayList<Banner> datas, ViewPager viewPager) {
            super(context, datas, viewPager,R.layout.item_banner);
        }

        @Override
        protected void onBind(int position, final Banner banner, ViewHolder holder) {
            SimpleDraweeView imageView = holder.bind(R.id.image);
            imageView.setImageURI(ImageUtil.parseImageUri(banner.getImgUrl()));
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (banner.getSkipType() == 0) {
                        ActivityUtil.create(context)
                                .go(WebViewActivity.class)
                                .put("data",banner.getBannerContent())
                                .put("type",1)
                                .start();
                    } else if (banner.getSkipType() == 1) {
                        ActivityUtil.create(context)
                                .go(WebViewActivity.class)
                                .put("url",banner.getBannerContent())
                                .start();
                    }
                }
            });
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (deleteVillageOb != null) {
            RxBus.get().unregister(Constant.DELETE_VILLAGE_ACTION,deleteVillageOb);
        }
    }
}
